package com.example.logining.filter;

import cn.hutool.json.JSONUtil;
import com.example.logining.domain.vo.LoginUser;
import com.example.logining.properties.JwtProperties;
import com.example.logining.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @title: JwtAuthenticationTokenFilter
 * @author: wywang
 * @date: 2024/11/15
 * @description:  Jwt 认证过滤器
 **/

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 1.获取token
        String token = request.getHeader("token");
        if(token == null){
            filterChain.doFilter(request, response);
            return;
        }

        // 2.解析token
        Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
        String userId = (String) claims.get("userId");

        // 3.从redis中获取用户对象
        String redisKey = "login:" + userId;
        String userStr = redisTemplate.opsForValue().get(redisKey);
        LoginUser loginUser = JSONUtil.toBean(userStr, LoginUser.class);

        // 4.判断用户是否过期或者为空
        if (loginUser == null) {
            throw new RuntimeException("用户未登录");
        }

        // 5.存入SecurityContextHolder中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }
}
